package com.chris.core.socket.netty.handler.heatbeat;

import com.chris.core.socket.netty.util.NettyRunTimeUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 字符串 - 编码 - 心跳处理器
 */
public class HeatBeatStringHandler extends ChannelInboundHandlerAdapter {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 自定义记录心跳idle次数
     * 超过次数可以结束contect
     * todo 需要对readIdleTimes 做超过次数中断 和 接收数据后计数归零机制
     */
    int readIdleTimes = 0;
    /**
     * 用户自定义心跳事件，重载
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
       // super.userEventTriggered(ctx, evt);
        if(evt instanceof IdleStateEvent)
        {
            IdleStateEvent event = (IdleStateEvent)evt;
            String eventType=null;
            switch (event.state()) {
                case READER_IDLE:
                    eventType="读空闲";
                    ctx.writeAndFlush("read-ping"+ NettyRunTimeUtil.runTimeBreakMark);
                    break;
                case  WRITER_IDLE:
                    eventType="写空闲";
                    ctx.writeAndFlush("write-ping"+NettyRunTimeUtil.runTimeBreakMark);
                    break;
                case ALL_IDLE:
                    eventType="读写空闲";
                    break;
            }
           // log.debug("心跳:"+eventType);
        }
    }
}
